/*
 * Copyright 2006 George Georgovassilis <g.georgovassilis[at]gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gwtwidgets.server.spring;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.user.client.rpc.RemoteService;

/**
 * Utilities for internal use
 * 
 * @author g.georgovassilis[at]gmail.com
 * 
 */
public class ReflectionUtils {
    public static Class[] getImplementedInterfaces(Class clazz) {
	Set/*<Class>*/ interfaces = getInterfaces(clazz);
	for (Iterator iter = interfaces.iterator(); iter.hasNext();) {
		Class c = (Class) iter.next();
	    try {
			c.asSubclass(RemoteService.class);
		} catch (ClassCastException e) {
			iter.remove();
		}
	}
//	for (Iterator<Class> ite = interfaces.iterator(); ite.hasNext();) {
//	    Class<?> c = ite.next();
//	    try {
//		c.asSubclass(RemoteService.class);
//	    } catch (ClassCastException e) {
//		ite.remove();
//	    }
//	}
//	return interfaces.toArray(new Class[interfaces.size()]);
	Class[] ret = new Class[interfaces.size()];
	interfaces.toArray(ret);
	return ret;

    }

    public static Set/*<Class>*/ getInterfaces(Class c) {
	Class interfaces[] = c.getInterfaces();
	Set/*<Class>*/ classes = new HashSet/*<Class>*/();
	if (interfaces == null)
	    return classes;
	Collections.addAll(classes, interfaces);
//	for (Class cl : interfaces) {
//	    classes.addAll(getInterfaces(cl));
//	}
	for (int i = 0; i < interfaces.length; i++) {
		classes.addAll(getInterfaces(interfaces[i]));
	}
	return classes;
    }

}
